#include "los_swtmr.h"
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "los_task.h"
#include "ohos_run.h"

void Timer1_Callback(uint32_t arg);
void Timer2_Callback(uint32_t arg);

#define LOSCFG_BASE_CORE_SWTMR_ALIGN = 1
#define TASK_PRIO 5


UINT32 g_timercount1 = 0;
UINT32 g_timercount2 = 0;
UINT32 g_testTaskId01;


void Timer1_Callback(uint32_t arg) // 回调函数1
{
    unsigned long tick_last1;
    g_timercount1++;
    tick_last1=(UINT32)LOS_TickCountGet(); // 获取当前Tick数
    printf("g_timercount1=%d\n",g_timercount1);
    printf("tick_last1=%d\n",tick_last1);
}

void Timer2_Callback(uint32_t arg) // 回调函数2
{
    unsigned long tick_last2;
    tick_last2=(UINT32)LOS_TickCountGet();
    g_timercount2 ++;
    printf("g_timercount2=%d\n",g_timercount2);
    printf("tick_last2=%d\n",tick_last2);
}

void Timer_example(void)
{
    UINT32 id1;
    UINT32 id2; // timer id
    UINT32 uwTick;

    /* 创建单次软件定时器，Tick数为1000，启动到1000Tick数时执行回调函数1 */
    LOS_SwtmrCreate (1000, LOS_SWTMR_MODE_ONCE, Timer1_Callback, &id1, 1, OS_SWTMR_ROUSES_ALLOW, OS_SWTMR_ALIGN_INSENSITIVE);
    
    /* 创建周期性软件定时器，每100Tick数执行回调函数2 */
    LOS_SwtmrCreate(100, LOS_SWTMR_MODE_PERIOD, Timer2_Callback, &id2, 1, OS_SWTMR_ROUSES_ALLOW, OS_SWTMR_ALIGN_INSENSITIVE);
    printf("create Timer1 success\n");

    LOS_SwtmrStart (id1); //启动单次软件定时器
    printf("start Timer1 success\n");
    LOS_TaskDelay(200); // 延时200Tick数
    LOS_SwtmrTimeGet(id1, &uwTick); // 获得单次软件定时器剩余Tick数
    printf("uwTick =%d\n", uwTick);

    LOS_SwtmrStop(id1); // 停止软件定时器
    printf("stop Timer1 success\n");
    

    LOS_SwtmrStart(id1);
    LOS_TaskDelay(1000);
    LOS_SwtmrDelete(id1); // 删除软件定时器
    printf("delete Timer1 success\n");

    LOS_SwtmrStart(id2); // 启动周期性软件定时器
    printf("start Timer2\n");

    LOS_TaskDelay(1000);
    LOS_SwtmrStop(id2);
    LOS_SwtmrDelete(id2);
}

UINT32 Example_TaskEntry(VOID)
{
    UINT32 ret;
    TSK_INIT_PARAM_S task1;
    /* 锁任务调度 */
    LOS_TaskLock();

    /* 创建任务1 */
    ret = memset_s(&task1, sizeof(TSK_INIT_PARAM_S), 0, sizeof(TSK_INIT_PARAM_S));
    if (ret != 0) {
        printf("memset_s fail!\r\n");
    }
    task1.pfnTaskEntry = (TSK_ENTRY_FUNC)Timer_example;
    task1.pcName = "TimerTsk";
    task1.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE;
    task1.usTaskPrio = TASK_PRIO;
    ret = LOS_TaskCreate(&g_testTaskId01, &task1);
    if (ret != LOS_OK) {
        printf("TimerTsk create failed.\n");
        return LOS_NOK;
    }

    /* 解锁任务调度 */
    LOS_TaskUnlock();

    return LOS_OK;
}

OHOS_APP_RUN(Example_TaskEntry);